<?php

namespace app\admin\controller;

use app\model\BizGoodsTicketModel;
use app\model\BizGoodsOrderModel;
use app\model\BizGoodsModel;
use app\model\BizModel;
use support\Request;
use support\Response;
use Exception;

/**
 * 核销码订单控制器
 * 
 * 用于管理核销码订单相关功能
 * 包含查询、搜索、核销等功能
 */
class BizTicketController
{
    /**
     * 获取核销码订单列表
     * @param Request $request
     * @return Response
     */
    public function index(Request $request): Response
    {
        try {
            $current = (int)$request->get('current', 1);
            $pageSize = (int)$request->get('pageSize', 10);
            $search = $request->get('search', ''); // 搜索关键词
            $phone = $request->get('phone', ''); // 手机号搜索
            $goods_name = $request->get('goods_name', ''); // 商品名称搜索
            $status = $request->get('status', ''); // 状态筛选
            
            $query = BizGoodsTicketModel::query()
                ->select('*')
                ->orderBy('created_at', 'desc')
                ->orderBy('id', 'desc');
            
            // 如果有搜索关键词，添加搜索条件
            if (!empty($search)) {
                $query->where(function($q) use ($search) {
                    $q->where('code', 'like', '%' . $search . '%')
                      ->orWhere('phone', 'like', '%' . $search . '%')
                      ->orWhere('goods_name', 'like', '%' . $search . '%')
                      ->orWhere('biz_name', 'like', '%' . $search . '%');
                });
            }
            
            // 手机号搜索
            if (!empty($phone)) {
                $query->where('phone', 'like', '%' . $phone . '%');
            }
            
            // 商品名称搜索
            if (!empty($goods_name)) {
                $query->where('goods_name', 'like', '%' . $goods_name . '%');
            }
            
            // 状态筛选
            if ($status !== '') {
                $query->where('status', $status);
            }
                
            $total = $query->count();
            $list = $query->offset(($current - 1) * $pageSize)
                ->limit($pageSize)
                ->get();

            foreach ($list as &$item) {
                $item['created_at'] = date('Y-m-d H:i:s', $item->created_at);
                $item['updated_at'] = date('Y-m-d H:i:s', $item->updated_at);
                if ($item->used_at) {
                    $item['used_at'] = date('Y-m-d H:i:s', $item->used_at);
                }
                $item['status_text'] = $item->getStatusTextAttribute();
            }
                
            return json([
                'data' => [
                    'list' => $list,
                    'total' => $total
                ],
                'msg' => '获取成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取核销码订单详情
     * @param Request $request
     * @return Response
     */
    public function detail(Request $request): Response
    {
        try {
            $id = $request->get('id');
            
            if (empty($id)) {
                throw new Exception('参数错误');
            }

            $ticket = BizGoodsTicketModel::find($id);
            if (!$ticket) {
                throw new Exception('核销码订单不存在');
            }

            $ticket['created_at'] = date('Y-m-d H:i:s', $ticket->created_at);
            $ticket['updated_at'] = date('Y-m-d H:i:s', $ticket->updated_at);
            if ($ticket->used_at) {
                $ticket['used_at'] = date('Y-m-d H:i:s', $ticket->used_at);
            }
            $ticket['status_text'] = $ticket->getStatusTextAttribute();

            return json([
                'data' => $ticket,
                'msg' => '获取成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }



    /**
     * 删除核销码订单
     * @param Request $request
     * @return Response
     */
    public function delete(Request $request): Response
    {
        try {
            $id = $request->post('id');
            
            if (empty($id)) {
                throw new Exception('参数错误');
            }

            $ticket = BizGoodsTicketModel::find($id);
            if (!$ticket) {
                throw new Exception('核销码订单不存在');
            }

            if (!$ticket->delete()) {
                throw new Exception('删除失败');
            }

            return json([
                'data' => null,
                'msg' => '删除成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 使用核销码
     * @param Request $request
     * @return Response
     */
    public function use(Request $request): Response
    {
        try {
            $id = $request->post('id');
            
            if (empty($id)) {
                throw new Exception('参数错误');
            }

            $ticket = BizGoodsTicketModel::find($id);
            if (!$ticket) {
                throw new Exception('核销码订单不存在');
            }

            if (!$ticket->isAvailable()) {
                throw new Exception('核销码已使用或已过期');
            }

            if (!$ticket->use()) {
                throw new Exception('核销失败');
            }

            return json([
                'data' => $ticket,
                'msg' => '核销成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 根据手机号和商品名称搜索核销码
     * @param Request $request
     * @return Response
     */
    public function search(Request $request): Response
    {
        try {
            $phone = $request->get('phone', '');
            $goods_name = $request->get('goods_name', '');
            $current = (int)$request->get('current', 1);
            $pageSize = (int)$request->get('pageSize', 10);
            
            $query = BizGoodsTicketModel::query()
                ->select('*')
                ->orderBy('created_at', 'desc');
            
            // 手机号搜索
            if (!empty($phone)) {
                $query->where('phone', 'like', '%' . $phone . '%');
            }
            
            // 商品名称搜索
            if (!empty($goods_name)) {
                $query->where('goods_name', 'like', '%' . $goods_name . '%');
            }
            
            // 如果两个条件都为空，返回空结果
            if (empty($phone) && empty($goods_name)) {
                return json([
                    'data' => [
                        'list' => [],
                        'total' => 0
                    ],
                    'msg' => '请输入搜索条件',
                    'code' => 20000
                ]);
            }
                
            $total = $query->count();
            $list = $query->offset(($current - 1) * $pageSize)
                ->limit($pageSize)
                ->get();

            foreach ($list as &$item) {
                $item['created_at'] = date('Y-m-d H:i:s', $item->created_at);
                $item['updated_at'] = date('Y-m-d H:i:s', $item->updated_at);
                if ($item->used_at) {
                    $item['used_at'] = date('Y-m-d H:i:s', $item->used_at);
                }
                $item['status_text'] = $item->getStatusTextAttribute();
            }
                
            return json([
                'data' => [
                    'list' => $list,
                    'total' => $total
                ],
                'msg' => '搜索成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }
} 